package com.my.algorithmlearning.leetcode;

/**
 * @ClassName Medium_208_Trie
 * @Description 优秀题解：https://leetcode.cn/problems/implement-trie-prefix-tree/solutions/721050/fu-xue-ming-zhu-cong-er-cha-shu-shuo-qi-628gs/
 * @Author wanghaiwei
 * @Date 2023/6/15 10:36
 */
public class Medium_208_Trie {
    WordTreeNode root;

    public Medium_208_Trie() {
        root = new WordTreeNode();
    }

    public void insert(String word) {
        if (word == null || word.length() == 0) {
            return;
        }
        WordTreeNode currCharNode = root;
        for (int i = 0; i < word.length(); i++) {
            int charIndex = word.charAt(i) - 'a';
            if (currCharNode.children[charIndex] == null) {
                currCharNode.children[charIndex] = new WordTreeNode();
            }
            currCharNode = currCharNode.children[charIndex];
        }
        currCharNode.isWord = true;
    }

    public boolean search(String word) {
        if (word == null || word.length() == 0) {
            return false;
        }
        WordTreeNode currCharNode = root;
        for (int i = 0; i < word.length(); i++) {
            int charIndex = word.charAt(i) - 'a';
            if (currCharNode.children[charIndex] == null) {
                return false;
            }
            currCharNode = currCharNode.children[charIndex];
        }
        return currCharNode.isWord;
    }

    public boolean startsWith(String prefix) {
        if (prefix == null || prefix.length() == 0) {
            return false;
        }
        WordTreeNode currCharNode = root;
        for (int i = 0; i < prefix.length(); i++) {
            int charIndex = prefix.charAt(i) - 'a';
            if (currCharNode.children[charIndex] == null) {
                return false;
            }
            currCharNode = currCharNode.children[charIndex];
        }
        return currCharNode != null;
    }
}

class WordTreeNode {
    boolean isWord;
    WordTreeNode[] children;

    public WordTreeNode() {
        this.isWord = false;
        children = new WordTreeNode[26];
    }
}
